import axios, { AxiosError, type AxiosRequestConfig, type AxiosResponse } from 'axios';
import { customRef } from 'vue';
export const loading = customRef((track, trigger) => {
  let count = 0;
  return {
    get() {
      track();
      return count > 0;
    },
    set(value) {
      count += value ? 1 : -1;
      trigger();
    }
  };
});

const service = axios.create({
  baseURL: '/api',
  timeout: 50000
});

service.interceptors.request.use(
  config => {
    loading.value = true;
    return config;
  },
  error => {
    console.log(error, 1);
    return Promise.reject(error);
  }
);
service.interceptors.response.use(
  ({ data }) => {
    loading.value = false;
    if (data.code === 0) {
      return data;
    } else if (data.code === undefined) {
      return data;
    } else {
      console.log(data, 3);
    }
  },
  error => {
    console.log(error, 2);
    return Promise.reject(error);
  }
);

export default {
  get(url: string, params?: object, config?: AxiosRequestConfig) {
    return service.get(url, { params, ...config });
  },
  post(url: string, data?: object, config?: AxiosRequestConfig) {
    return service.post(url, data, config);
  }
};
